<template>
  <el-cascader
    v-model="select"
    v-bind="$attrs"
    v-on="$listeners"
    v-loading="loading"
    element-loading-spinner="el-icon-loading"
    :options="industryType"
    :props="props"
    @change="handleChange"
  ></el-cascader>
</template>

<script>
import { mapGetters } from 'vuex'
import { cascaderFind } from '@vimi/utils-tool'

export default {
  components: {},
  props: {
    value: String,
  },
  model: {
    prop: 'value',
    event: 'select',
  },
  data() {
    return {
      loading: false,
      select: '',
      props: {
        label: 'value',
        value: 'code',
      },
    }
  },
  computed: {
    ...mapGetters(['industryType']),
  },
  watch: {
    value(val) {
      if (val !== this.select) {
        this.initSelect(val)
      }
    },
  },
  created() {
    this.loading = true
    this.$store.dispatch('getIndustryType').finally(() => {
      this.loading = false
      this.initSelect(this.value)
    })
  },
  mounted() {},
  methods: {
    initSelect(val) {
      const { code } = this.findSelect(val)
      this.select = code || ''
    },
    handleChange(val) {
      const select = Array.isArray(val) && val.length ? val[val.length - 1] : val || ''
      const item = this.findSelect(select)
      this.select = select
      this.$emit('select', select, item)
    },
    findSelect(val) {
      if (!val) {
        return {}
      }
      return cascaderFind(this.industryType, item => item.id === val) || {}
    },
  },
}
</script>

<style lang="scss" scoped></style>
